package com.gxa.hualianeshop.interceptor;

import com.gxa.hualianeshop.entity.pojo.User;
import com.gxa.hualianeshop.service.UserService;
import com.gxa.hualianeshop.threadLocal.UserThreadLocal;
import org.apache.dubbo.config.annotation.Reference;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @author bill
 * @date 2023/7/10 16:23
 */
@Component
public class TokenInterceptor implements HandlerInterceptor {

    @Reference
    UserService userService;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        // 拦截用户携带的请求头
        String token = request.getHeader("token");


        User user = userService.QueryUserByToken(token);

        // 通过ThreadLocal
        UserThreadLocal.set(user);


        return false;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        // 在拦截器的后置处理: 销毁线程作用域中的内容
        UserThreadLocal.remove();
    }
}
